<template>
    <div class="notice-list" v-loading="loading">
        <common-list @resert="resert" ref="commonListRef">
            <template #message>
                <div class="message">
                    <el-descriptions column="4">
                        <el-descriptions-item label="设备编号">{{ equipmentCode == "" ? "未选择" : equipmentCode }}</el-descriptions-item>
                        <el-descriptions-item label="设备名称">{{ quipment.name == null ? "暂无" : quipment.name }}</el-descriptions-item>
                        <el-descriptions-item label="设备管理员">{{ quipment.manager == null ? "暂无" : quipment.manager }}</el-descriptions-item>
                        <el-descriptions-item label="计划周期">{{ cycleTypeName == "" ? "未选择" : cycleTypeName }}</el-descriptions-item>
                        <el-descriptions-item label="计划日期">{{ formData.execDate }}</el-descriptions-item>
                        <el-descriptions-item label="分派人员">
                            <el-select v-model="personId" placeholder="请选择分派人员" style="width: 60%" :suffix-icon="CaretBottom">
                                <el-option v-for="item in personnel" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-descriptions-item>
                        <el-descriptions-item label=""></el-descriptions-item>
                        <el-descriptions-item label="">
                            <el-button class="switchover" @click="frontClick" :ref="frontChange">{{ front }}</el-button>
                            <el-button class="switchover" @click="laterClick" :ref="laterChange">{{ later }}</el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
            </template>
            <template #StructureName="{ scope }">
                <div :class="[scope.scope.row.state == 3 ? 'useless' : '']">{{ scope.scope.row.structureName }}</div>
            </template>
            <template #ItemCount="{ scope }">
                <div style="color: #0081e3; cursor: pointer" @click="lineClick(scope)">{{ scope.scope.row.itemCount }}</div>
            </template>
            <template #operate="{ scope }">
                <el-switch
                    v-model="scope.scope.row.state"
                    inline-prompt
                    :disabled="scope.scope.row.state === '3' || (isShow && modifiedTime < nowTime)"
                    active-text="开"
                    inactive-text="关"
                    active-value="1"
                    inactive-value="3"
                    @change="stateChange($event, scope.scope.row)"
                />
            </template>
            <template #btns="{ scope }">
                <div class="btns1">
                    <text class="first"> 一级保养 </text>
                    <text class="second" @click="secondMaintain"> 二级保养 </text>
                </div>
                <div class="btns">
                    <w-button class="config-btn" @click="batchClose">一键关闭</w-button>
                </div>
            </template>
        </common-list>
        <!-- 操作(详情) -->
        <el-dialog v-model="detail" title="" width="50%" :close-on-click-modal="false">
            <div class="card-header">
                <span>{{ editFormData.structureTypeText }}-{{ editFormData.structureName }} (检查项：{{ editFormData.itemCount }})</span>
            </div>
            <el-table :data="editFormData.itemDetails" height="400" style="width: 100%">
                <el-table-column type="index" label="序号" min-width="50" />
                <el-table-column prop="location" label="位置" min-width="120" />
                <el-table-column prop="itemName" label="检查项" min-width="220" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="detail = false">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { provide, reactive, ref, nextTick } from "vue";
import { CaretBottom } from "@element-plus/icons-vue";
import { formConfig, tableConfig } from "./firstConfig";
import { getMaintain, getPlanType, getPersonnel, getQuipment, setState, setBatchState } from "@/service/api/planManagement.js";
import { useRoute, useRouter } from "vue-router";

const loading = ref(false);
const route = useRoute();
const router = useRouter();
const commonListRef = ref(null);
const personnel = ref();
const quipment = ref({});
const front = ref();
const later = ref();
const toChange = ref(false);
const isShow = ref(true);
const stateData = reactive({
    planDetailId: "",
    execDate: "",
    state: ""
});
const equipmentCode = ref(route.query.equipmentCode);
const cycleTypeName = ref(route.query.cycleTypeName);
const personId = ref();
const formData = reactive({
    equipmentId: route.query.equipmentId,
    planCycleType: route.query.planCycleType,
    execDate: route.query.execDate,
    maintenanceType: route.query.maintenanceType,
    structureType: "",
    structureName: "",
    personId: personId.value
});
const detail = ref(false);
const editFormData = ref();
const nowTime = ref(new Date().getTime());
formData.execDate = formData.execDate.substring(0, 19);
formData.execDate = formData.execDate.replace(/-/g, "-");
const modifiedTime = new Date(formData.execDate).getTime();

const secondMaintain = () => {
    router.push({
        path: "/main/planManagement/secondMaintain",
        query: {
            execDate: formData.execDate,
            equipmentId: formData.equipmentId,
            planCycleType: formData.planCycleType,
            maintenanceType: 2,
            equipmentCode: equipmentCode.value,
            cycleTypeName: cycleTypeName.value
        }
    });
};
const frontChange = () => {
    if (formData.planCycleType == 1) {
        front.value = "前一周";
    } else if (formData.planCycleType == 2) {
        front.value = "前一月";
    } else if (formData.planCycleType == 3) {
        front.value = "前一季";
    } else if (formData.planCycleType == 4) {
        front.value = "前一年";
    } else {
        front.value = "前一天";
    }
};
const laterChange = () => {
    if (formData.planCycleType == 1) {
        later.value = "后一周";
    } else if (formData.planCycleType == 2) {
        later.value = "后一月";
    } else if (formData.planCycleType == 3) {
        later.value = "后一季";
    } else if (formData.planCycleType == 4) {
        later.value = "后一年";
    } else {
        later.value = "后一天";
    }
};
const frontClick = () => {
    if (front.value == "前一周") {
        formData.execDate = dateAddDays(formData.execDate, -7);
    } else if (front.value == "前一月") {
        formData.execDate = dateAddDays(formData.execDate, -30);
    } else if (front.value == "前一季") {
        formData.execDate = dateAddDays(formData.execDate, -90);
    } else if (front.value == "前一年") {
        formData.execDate = dateAddDays(formData.execDate, -365);
    } else {
        formData.execDate = dateAddDays(formData.execDate, -1);
    }
    formData.execDate = formData.execDate.substring(0, 19);
    formData.execDate = formData.execDate.replace(/-/g, "-");
    const modifiedTime = new Date(formData.execDate).getTime();
    if (modifiedTime < nowTime.value) {
        isShow.value = true;
    } else {
        isShow.value = false;
    }
    commonListRef.value.tableRef.getTableList();
};
const laterClick = () => {
    if (later.value == "后一周") {
        formData.execDate = dateAddDays(formData.execDate, 7);
    } else if (later.value == "后一月") {
        formData.execDate = dateAddDays(formData.execDate, 30);
    } else if (later.value == "后一季") {
        formData.execDate = dateAddDays(formData.execDate, 90);
    } else if (later.value == "后一年") {
        formData.execDate = dateAddDays(formData.execDate, 365);
    } else {
        formData.execDate = dateAddDays(formData.execDate, 1);
    }
    formData.execDate = formData.execDate.substring(0, 19);
    formData.execDate = formData.execDate.replace(/-/g, "-");
    const modifiedTime = new Date(formData.execDate).getTime();
    if (modifiedTime > nowTime.value) {
        isShow.value = false;
    } else {
        isShow.value = true;
    }
    commonListRef.value.tableRef.getTableList();
};
function dateAddDays(dateStr, dayCount) {
    let tempDate = new Date(dateStr.replace(/-/g, "/")); //把日期字符串转换成日期格式
    let resultDate = new Date((tempDate / 1000 + 86400 * dayCount) * 1000); //增加n天后的日期
    let resultDateStr =
        resultDate.getFullYear() +
        "-" +
        (resultDate.getMonth() + 1 < 10 ? "0" + (resultDate.getMonth() + 1) : resultDate.getMonth() + 1) +
        "-" +
        (resultDate.getDate() < 10 ? "0" + resultDate.getDate() : resultDate.getDate()); //将日期转化为字符串格式
    return resultDateStr;
}
getPlanType().then((res) => {
    if (res.code === 200) {
        formConfig[0].options = res.data.map((item) => ({
            label: item.name,
            value: item.value
        }));
    }
});
function Quipment() {
    if (formData.equipmentId == null || formData.equipmentId == "") {
        getQuipment({ equipmentId: 0 }).then((res) => {
            if (res.code === 200) {
                quipment.value = res.data;
            }
        });
    } else {
        getQuipment({ equipmentId: formData.equipmentId }).then((res) => {
            if (res.code === 200) {
                quipment.value = res.data;
            }
        });
    }
}
function Personnel() {
    if (formData.equipmentId == null || formData.equipmentId == "") {
        getPersonnel({ equipmentId: 0 }).then((res) => {
            if (res.code === 200) {
                personnel.value = null;
            }
        });
    } else {
        getPersonnel({ equipmentId: formData.equipmentId }).then((res) => {
            if (res.code === 200) {
                personnel.value = res.data.map((item) => ({
                    label: item.name,
                    value: item.value
                }));
            }
        });
    }
}
const stateChange = (val, row) => {
    if (!toChange.value) {
        toChange.value = true;
    } else {
        if (val === 3) {
            stateData.state = false;
        } else {
            stateData.state = true;
        }
        stateData.planDetailId = row.id;
        stateData.execDate = formData.execDate;
        setState(stateData).then((res) => {
            if (res.code === 200) {
                ElMessage.success("修改成功！");
                commonListRef.value.tableRef.getTableList();
            } else {
                ElMessage.error(res.message);
                row.State = !val;
            }
        });
    }
};

async function batchClose() {
    await nextTick(() => {
        formData.execDate = formData.execDate.substring(0, 19);
        formData.execDate = formData.execDate.replace(/-/g, "-");
        const modifiedTime = new Date(formData.execDate).getTime();
        const Beclose = commonListRef.value.tableRef.tableData.map((item) => item.state);
        if (modifiedTime < nowTime.value) {
            ElMessage.warning("当前日期无法操作！");
        } else if (Beclose.indexOf("1") === -1) {
            ElMessage.warning("当前日期无可关闭的计划！");
        } else {
            ElMessageBox.confirm("确定一键关闭吗?", "关闭", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "一键关闭"
            })
                .then(() => {
                    loading.value = true;
                    setBatchState({ execDate: formData.execDate }).then((res) => {
                        loading.value = false;
                        if (res.code === 200) {
                            commonListRef.value.tableRef.getTableList();
                            ElMessage.success("关闭成功！");
                        } else {
                            ElMessage.error(res.message);
                        }
                    });
                })
                .catch(() => (loading.value = false));
        }
    });
}
Quipment();
Personnel();
const resert = () => {
    Object.keys(formData).forEach((key) => {
        if (key !== "equipmentId" && key !== "planCycleType" && key !== "execDate" && key !== "maintenanceType") {
            formData[key] = "";
        }
    });
};
const lineClick = (scope) => {
    editFormData.value = scope.scope.row;
    detail.value = true;
};
provide("formConfig", formConfig);
provide("tableConfig", tableConfig);
provide("formData", formData);
provide("apiFn", getMaintain);
</script>

<style lang="less" scoped>
.notice-list {
    .card-header {
        font-size: 16px;
        font-weight: 600;
        color: #1b3646;
        line-height: 22px;
        margin-top: -40px;
        padding-bottom: 20px;
    }
    .message {
        height: 112px;
        background: #ffffff;
        margin-bottom: 20px;
        :deep(.el-descriptions) {
            padding: 28px 20px 0 20px;
        }
    }
    .useless {
        text-decoration: line-through;
    }
    .btns1 {
        position: absolute;
        .first {
            color: #1b3646;
            font-size: 16px;
        }
        .second {
            color: #8c8c8c;
            font-size: 16px;
            margin-left: 25px;
            cursor: pointer;
        }
    }
    .btns {
        display: flex;
        .resert {
            border: 1px solid @main-color;
            color: @main-color;
        }
    }
    .switchover {
        border: 1px solid #00428e;
        color: #00428e;
        font-size: 14px;
    }
}
</style>
<style>
.el-descriptions__cell:last-child {
    display: flex;
    justify-content: flex-end;
}
</style>
